package com.share.wechat.file.controller;

import com.share.common.tools.ID.IDutils;
import com.share.common.tools.fille.Base64Util;
import com.share.wechat.file.service.FileService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/file/")
public class ImageController {
    private final Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private FileService fileService;
    //在配置文件中写的存放文件的位置
    @Value("${image.file.path}")
    private String imageFilePath;

    /**
     * 读取文件
     *
     * @param imageName 图片文件名称
     * @param response  相应
     */
    @Deprecated
    @RequestMapping(value = "getImage/{imageName}", produces = "image/png")
    public void getImageFromImageName(@PathVariable String imageName, HttpServletResponse response) {
        logger.info("this is into this method");

        if (StringUtils.isEmpty(imageName)) {
            logger.info("图片名称未知");
            return;
        }
        String image = fileService.readDataByFileName(imageName);

        try {
            ServletOutputStream outputStream = response.getOutputStream();

            outputStream.write(image.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error("获取图片的时候发生异常");
            logger.error(this.getClass().getName() + "发生异常" + e.getMessage() + e.getLocalizedMessage());
            e.printStackTrace();
        } finally {
            logger.error("那个王八蛋乱发请求 ,请管理员检查");
        }


    }

    @GetMapping("image/{imageName:.+}")
    public void getImageFile(@PathVariable String imageName, HttpServletResponse response) throws IOException {
        logger.info("文件的名字为" + imageName);
        if (!imageName.contains(".")) {
            logger.info("图片文件名错误" + imageName);
            return;
        }

        try (
                ServletOutputStream outputStream = response.getOutputStream();
                FileInputStream inputStream = new FileInputStream(imageFilePath + File.separator + imageName);
        ) {
            byte[] BYTE = new byte[8192];
            while ((inputStream.read(BYTE)) != -1) {
                outputStream.write(BYTE);
            }
        }


    }


    /**
     * 上传文件
     *
     * @param imageName 文件名称
     * @param file      文件
     * @return json格式对象
     */
    @GetMapping(value = "upload/{imageName}")
    public Map upLoadFile(@PathVariable String imageName, MultipartFile file) {
        Map<String, String> result = new HashMap<>(2);
        result.put("code", "error");
        if (StringUtils.isEmpty(imageName)) {
            imageName = IDutils.getUUIDNoLine() + "//" + IDutils.genImageName();
            logger.info("该图片为设置图片名称,图片名称设置为" + imageName);
        }
        if (file == null) {
            String type;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            logger.info("上传的文件原名称:" + fileName);
            // 判断文件类型
            type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    String imageDate = Base64Util.fileToBase64(file);
                    if (!StringUtils.isEmpty(imageDate)) {
                        if (!fileName.toUpperCase().endsWith("PNG") || fileName.toUpperCase().endsWith("JPG") || fileName.toUpperCase().endsWith("GIF")) {
                            imageName += "." + type;
                        }
                        fileService.saveFile(imageDate.getBytes(), imageName);
                        if (logger.isInfoEnabled()) {
                            logger.info("该文件的文件名为" + imageName);
                            logger.info("存贮文件成功");

                        }
                        result.put("code", "success");
                        result.put("msg", "上传成功");
                        result.put("fileName", imageName);
                    }

                } else {
                    result.put("msg", "文件名未知 文件类型未知");
                    logger.info("文件名未知 文件类型未知");
                    return result;
                }
            } else {
                result.put("msg", "获取不到文件类型");
            }


        }

        return result;

    }

    @RequestMapping("uploadImage")
    public void uploadFile(MultipartFile[] multipartFiles, HttpServletRequest request) throws IOException {
        String fileName = request.getSession().getServletContext().getRealPath("/") + "upload/";
        for (MultipartFile multipartFile : multipartFiles) {
            multipartFile.transferTo(new File(fileName + multipartFile.getOriginalFilename()));
        }


    }


}